package dao

import (
	"context"
	"gorm.io/gorm"
	"mall-admin-go/model"
)

type UserDao struct {
	*gorm.DB
}

func NewUserDao(ctx context.Context) *UserDao {
	return &UserDao{NewDBCliet(ctx)}
}

func (dao *UserDao) GetAllUser(conditions map[string]interface{}, page model.BasePage) (user []*model.User, total int64, err error) {
	err = dao.DB.Model(&model.User{}).Where(conditions).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	err = dao.DB.Model(&model.User{}).
		Offset((page.PageNum - 1) * (page.PageSize)).Limit(page.PageSize).
		Where(conditions).
		Find(&user).Error
	if err != nil {
		return nil, 0, err
	}
	return user, total, nil
}

func (dao *UserDao) GetAllUserByDate(conditions map[string]interface{}, page model.BasePage, StartDay, EndDay string) (user []*model.User, total int64, err error) {
	err = dao.DB.Model(&model.User{}).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	err = dao.DB.Model(&model.User{}).
		Offset((page.PageNum-1)*(page.PageSize)).Limit(page.PageSize).
		Where(conditions).Where("created_at BETWEEN ? AND ?", StartDay, EndDay).
		Find(&user).Error
	if err != nil {
		return nil, 0, err
	}
	return user, total, nil
}

func (dao *UserDao) GetUserByUid(uid string) (user *model.User, err error) {
	err = dao.DB.Model(&model.User{}).Where("uuid = ?", uid).Find(&user).Error
	return
}
